require('dotenv').config()
const TelegramBot = require('node-telegram-bot-api');
const express = require ('express')
const cors = require('cors');
const { query } = require('express');

const bot = new TelegramBot(process.env.API_BOT_TOKEN, {polling: true});
const webAppUrl = 'https://65c1-37-215-45-141.eu.ngrok.io'
const app = express()


app.use(express.json())
app.use(cors())

bot.on('message', async (msg) => {
  const chatId = msg.chat.id;
  const text = msg.text

  if (text == '/start') {
    await bot.sendMessage(chatId, 'Tap button below and fill the form', {
        reply_markup:{
            keyboard:[
                [{text: 'Form', web_app: {url: webAppUrl + '/form'}}]
            ]
        }
    });
  }


  if (text == '/order') {
    await bot.sendMessage(chatId, 'Take order', {
        reply_markup:{
            inline_keyboard:[
                [{text: 'Order', web_app: {url: webAppUrl}}]
            ]
        }
    });
  }

  if(msg?.web_app_data?.data) {
    try {
      const data = JSON.parse(msg?.web_app_data?.data)

      await bot.sendMessage(chatId, 'Well done!')
      await bot.sendMessage(chatId, 'Country: ' + data.country)
      await bot.sendMessage(chatId, 'Street: ' + data.street)

      setTimeout( async () => {
        await bot.sendMessage(chatId, 'All information in this chat')
      }, 3000)
    } catch (e) {
      console.log(e);
    }
  }
});

app.post('/web-data', async (req,res) => {
  const {queryId, products = [], totalPrice} = req.body
  try {
    await bot.answerWebAppQuery(queryId, {
      type: 'article',
      id: queryId,
      title: 'Sucsess pursche',
      input_message_content: {message_text: `We recived your order for ${totalPrice}, ${products.map(item => item.title).join(', ')}`}
    })
    console.log(totalPrice);
    return res.status(200).json({})
  } catch (e) {
    await bot.answerWebAppQuery(queryId, {
      type: 'article',
      id: queryId,
      title: 'Error',
      input_message_content: {message_text: 'Something goes wrong'}
    })
    return res.status(500).json({})    
  }
})

app.listen(process.env.PORT, () => console.log('server started on port ' + process.env.PORT))
